using System;

namespace Week3
{
    internal class Week3Text
    {
        public class Clock
        {
            private System.Timers.Timer timer;  //计时器，不过为什么头上写using System.Timers然后这里用Timer会有二义
            private DateTime time; //闹钟定时时间
            private bool Trigger;
            public DateTime Current { get; private set; }
            public event EventHandler Tick; //事件委托
            public event EventHandler Alarm;

            public Clock(DateTime t)
            {
                Current = DateTime.Now; //取现在时间
                time = t;
                timer = new System.Timers.Timer(1000); //1s为间隔
                timer.Elapsed += OnTime; //自定义功能绑定到已有计数器上
            }
            public void OnTime(object sender, System.Timers.ElapsedEventArgs e)
            {
                Current = Current.AddSeconds(1); //模拟运行
                Tick?.Invoke(this, EventArgs.Empty); //滴答事件触发
                if(!Trigger && Current>= time)
                {
                    Trigger = true;
                    Alarm?.Invoke(this, EventArgs.Empty);//响铃事件触发
                }
            }
            public void begin()
            {
                timer.Start();//开始
                Console.WriteLine("Begin！闹钟已开始运行！");
            }
        }

        static void Main(string[] args)
        {
            Console.Write("请输入定时（如5s请输入5）：");
            int n = Convert.ToInt32(Console.ReadLine());
            var alarmTime = DateTime.Now.AddSeconds(n);
            var alarmClock = new Clock(alarmTime);
            alarmClock.Tick += (s, e) => Console.WriteLine("Tick！当前时间为{0}",alarmClock.Current); //EventHandler传递s,e
            alarmClock.Alarm += (s, e) => Console.WriteLine("Alarm！抵达定时，时间到！");
            alarmClock.begin();
            Console.WriteLine("按任意键退出！");
            Console.ReadKey();
        }
    }
}